import { userLogin } from '@/api';
import { loginData } from '@/interfaces/aboutApi';
import router from '@/router';
import { Local } from '@/utils/storage';
import { commonEnums } from '@/enums';
import { ElMessage } from 'element-plus';

interface userInfo {
  username: string;
  sex: string;
  phoneNumber: string;
  avatar_url: string;
  roles: string[];
  create_time: string;
  update_time: string;
}
const useLoginStore = defineStore('LoginStore', {
  state: () => ({
    userInfo: {} as userInfo,
  }),
  actions: {
    setUserInfo(loginData: loginData) {
      userLogin(loginData)
        .then((res) => {
          ElMessage.success('登录成功，欢迎回来！');
          Local.setItem(commonEnums.TOKEN, JSON.stringify(res.result.token), 7 * 24 * 3600 * 1000);
          this.userInfo = {
            username: res.result.username,
            sex: res.result.sex,
            phoneNumber: res.result.phoneNumber,
            avatar_url: res.result.avatar_url,
            roles: res.result.roles,
            create_time: res.result.create_time,
            update_time: res.result.update_time,
          };
          router.push('/admin/home');
        })
        .catch((err) => err);
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'userInfo',
        storage: localStorage,
        paths: ['userInfo'],
      },
    ],
  },
});
export default useLoginStore;
